/*
 * @Author: Hugh Xie
 * @Date: 2022-03-01 12:41:40
 * @LastEditors: Hugh Xie
 * @LastEditTime: 2022-04-06 10:49:14
 * @FilePath: \frontend\src\utils\validator.js
 */
import { isNull, isUndefined, isEmpty } from 'lodash'

/**
 * 验证身份证号码
 * 15位时全为数字
 * 18位前17位为数字 最后一位是校验位 可能为数字或字符X
 * @param {*} value
 * @param {*} rules
 */
export const idCardValidator = (value, rules) => {
  if (value.length === 0) return false
  const reg = new RegExp(idCardPattern)
  return reg.test(value)
}

/**
 * 检验最少和最多字符限制
 * 交由每个rules下的min和max控制
 * @param {*} value
 * @param {*} rules
 */
export const minMaxValidator = (value, rules) => {
  if (isEmpty(value)) return false
  const { min, max } = rules
  const isEmptyMax = isNull(max) || isUndefined(max)
  const isEmptyMin = isNull(min) || isUndefined(min)
  const valueLength = value.length
  if (!isEmptyMin && valueLength < min) {
    rules.message = `请至少输入${min}位字符`
    return false
  }
  if (!isEmptyMax && valueLength > max) {
    rules.message = `最多只能输入${max}位字符`
    return false
  }
  return true
}

/**
 * 手机号码正则pattern
 */
export const telPattern = new RegExp(/^[1][3,4,5,6,7,8,9][0-9]{9}$/)

/**
 * 身份证号码正则pattern
 */
export const idCardPattern = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/)
/**
 * 电话号码正则pattern(手机，固定电话和加区号)
 */
export const phoneCardPattern = new RegExp(/(\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$/)
/**
 * 邮箱地址pattern
 */
export const emailPattern = new RegExp(/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/)

/**
 * 银行卡号校验
 * @type {RegExp}
 */
export const bankNumberPattern = new RegExp(/^[0-9]{10,19}$/)
/**
 * 护照号校验
 * @type {RegExp}
 */
export const passportPattern = new RegExp(/^((1[45]\d{7})|(G\d{8})|(P\d{7})|(S\d{7,8}))?$/)
/**
 * 营业执照号校验
 * @type {RegExp}
 */
export const businessPattern = new RegExp(/(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/)
/**
 * 邮编的校验
 * @type {RegExp}
 */
export const postCodePattern = new RegExp(/^[1-9][0-9]{5}$/)
